package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.DormTrippingRecord;
import com.example.chamberlainserver.Service.DormTrippingRecordService;
import com.example.chamberlainserver.Vo.Request.DormTripping.DormTrippingRecordQuery;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 宿舍跳闸记录控制器
 */
@RestController
@RequestMapping("/dormTrippingRecord")
public class DormTrippingRecordController {

    @Autowired
    private DormTrippingRecordService dormTrippingRecordService;

    /**
     * 添加跳闸记录
     * @param record 跳闸记录信息
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseEntity<ApiResponse<DormTrippingRecord>> addRecord(@RequestBody DormTrippingRecord record) {
        try {
            // 如果跳闸时间为空，设置为当前时间
            if (record.getTrippingTime() == null) {
                record.setTrippingTime(LocalDateTime.now());
            }
            
            // 如果处理状态为空，默认为未处理
            if (record.getIsHandled() == null) {
                record.setIsHandled(false);
            }
            
            DormTrippingRecord addedRecord = dormTrippingRecordService.addRecord(record);
            return ResponseEntity.ok(ApiResponse.success("添加跳闸记录成功", addedRecord));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("添加跳闸记录失败：" + e.getMessage()));
        }
    }

    /**
     * 更新跳闸记录
     * @param record 跳闸记录信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public ResponseEntity<ApiResponse<DormTrippingRecord>> updateRecord(@RequestBody DormTrippingRecord record) {
        try {
            DormTrippingRecord updatedRecord = dormTrippingRecordService.updateRecord(record);
            return ResponseEntity.ok(ApiResponse.success("更新跳闸记录成功", updatedRecord));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新跳闸记录失败：" + e.getMessage()));
        }
    }

    /**
     * 删除跳闸记录
     * @param id 记录ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<ApiResponse<Boolean>> deleteRecord(@PathVariable Integer id) {
        try {
            boolean result = dormTrippingRecordService.deleteRecord(id);
            return ResponseEntity.ok(ApiResponse.success("删除跳闸记录成功", result));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除跳闸记录失败：" + e.getMessage()));
        }
    }

    /**
     * 根据ID获取跳闸记录
     * @param id 记录ID
     * @return 跳闸记录信息
     */
    @GetMapping("/get/{id}")
    public ResponseEntity<ApiResponse<DormTrippingRecord>> getRecordById(@PathVariable Integer id) {
        try {
            DormTrippingRecord record = dormTrippingRecordService.getRecordById(id);
            return ResponseEntity.ok(ApiResponse.success("获取跳闸记录成功", record));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取跳闸记录失败：" + e.getMessage()));
        }
    }

    /**
     * 获取所有跳闸记录
     * @return 跳闸记录列表
     */
    @GetMapping("/all")
    public ResponseEntity<ApiResponse<List<DormTrippingRecord>>> getAllRecords() {
        try {
            List<DormTrippingRecord> records = dormTrippingRecordService.getAllRecords();
            return ResponseEntity.ok(ApiResponse.success("获取所有跳闸记录成功", records));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取所有跳闸记录失败：" + e.getMessage()));
        }
    }

    /**
     * 根据宿舍号获取跳闸记录
     * @param dormitoryNum 宿舍号
     * @return 跳闸记录列表
     */
    @GetMapping("/getByDormitory")
    public ResponseEntity<ApiResponse<List<DormTrippingRecord>>> getRecordsByDormitoryNum(
            @RequestParam String dormitoryNum) {
        try {
            List<DormTrippingRecord> records = dormTrippingRecordService.getRecordsByDormitoryNum(dormitoryNum);
            return ResponseEntity.ok(ApiResponse.success("获取宿舍跳闸记录成功", records));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取宿舍跳闸记录失败：" + e.getMessage()));
        }
    }

    /**
     * 根据班级名称获取跳闸记录
     * @param className 班级名称
     * @return 跳闸记录列表
     */
    @GetMapping("/getByClass")
    public ResponseEntity<ApiResponse<List<DormTrippingRecord>>> getRecordsByClassName(
            @RequestParam String className) {
        try {
            List<DormTrippingRecord> records = dormTrippingRecordService.getRecordsByClassName(className);
            return ResponseEntity.ok(ApiResponse.success("获取班级跳闸记录成功", records));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取班级跳闸记录失败：" + e.getMessage()));
        }
    }

    /**
     * 根据辅导员姓名获取跳闸记录
     * @param counselor 辅导员姓名
     * @return 跳闸记录列表
     */
    @GetMapping("/getByCounselor")
    public ResponseEntity<ApiResponse<List<DormTrippingRecord>>> getRecordsByCounselor(
            @RequestParam String counselor) {
        try {
            List<DormTrippingRecord> records = dormTrippingRecordService.getRecordsByCounselor(counselor);
            return ResponseEntity.ok(ApiResponse.success("获取辅导员跳闸记录成功", records));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取辅导员跳闸记录失败：" + e.getMessage()));
        }
    }

    /**
     * 根据处理状态获取跳闸记录
     * @param isHandled 处理状态
     * @return 跳闸记录列表
     */
    @GetMapping("/getByStatus")
    public ResponseEntity<ApiResponse<List<DormTrippingRecord>>> getRecordsByHandleStatus(
            @RequestParam Boolean isHandled) {
        try {
            List<DormTrippingRecord> records = dormTrippingRecordService.getRecordsByHandleStatus(isHandled);
            return ResponseEntity.ok(ApiResponse.success("获取处理状态跳闸记录成功", records));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取处理状态跳闸记录失败：" + e.getMessage()));
        }
    }

    /**
     * 分页查询跳闸记录
     * @param current 当前页码
     * @param pageSize 每页大小
     * @param dormitoryNum 宿舍号
     * @param studentName 学生姓名
     * @param className 班级名称
     * @param counselor 辅导员姓名
     * @param isHandled 处理状态
     * @param minTrippingPower 最小跳闸功率
     * @param maxTrippingPower 最大跳闸功率
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 分页结果
     */
    @GetMapping("/pagedList")
    public ResponseEntity<ApiResponse<PageResult<DormTrippingRecord>>> getPagedRecordList(
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "dormitoryNum", required = false) String dormitoryNum,
            @RequestParam(value = "studentName", required = false) String studentName,
            @RequestParam(value = "className", required = false) String className,
            @RequestParam(value = "counselor", required = false) String counselor,
            @RequestParam(value = "isHandled", required = false) Boolean isHandled,
            @RequestParam(value = "minTrippingPower", required = false) BigDecimal minTrippingPower,
            @RequestParam(value = "maxTrippingPower", required = false) BigDecimal maxTrippingPower,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        try {
            DormTrippingRecordQuery recordQuery = new DormTrippingRecordQuery();
            recordQuery.setCurrent(current);
            recordQuery.setPageSize(pageSize);
            recordQuery.setDormitoryNum(dormitoryNum);
            recordQuery.setStudentName(studentName);
            recordQuery.setClassName(className);
            recordQuery.setCounselor(counselor);
            recordQuery.setIsHandled(isHandled);
            recordQuery.setMinTrippingPower(minTrippingPower);
            recordQuery.setMaxTrippingPower(maxTrippingPower);
            recordQuery.setStartDate(startDate);
            recordQuery.setEndDate(endDate);
            
            PageResult<DormTrippingRecord> pageResult = dormTrippingRecordService.getPagedRecordList(recordQuery);
            return ResponseEntity.ok(ApiResponse.success("获取跳闸记录列表成功", pageResult));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取跳闸记录列表失败: " + e.getMessage()));
        }
    }
}